package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 自媒体素材管理
     *
     * @param multipartFile
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        try {
            //todo 1.将图片上传到minio中
            //原始文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //截取后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //文件名
            String fileName = UUID.randomUUID().toString() + suffix;

            String imgUrl = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());
            //todo 2.将minion返回的图片的url 地址 保存到数据库表中,wm_material
            WmMaterial wmMaterial = new WmMaterial();
            //todo 先写死,后面通过 ThreadLocal 中获取userId
            wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
            wmMaterial.setUrl(imgUrl);
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);

            //todo 3.封装结果返回
            return ResponseResult.okResult(wmMaterial);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //todo 1.校验参数
        dto.checkParam();
        //todo 2.分页查询,条件查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.<WmMaterial>lambdaQuery();

        lambdaQuery.eq(dto.getIsCollection() != null && dto.getIsCollection().equals((short)1),WmMaterial::getIsCollection,dto.getIsCollection());
        //用户
        lambdaQuery.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //倒序排序
        lambdaQuery.orderByDesc(WmMaterial::getCreatedTime);
        this.page(page,lambdaQuery);
        //todo 3.封装返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        responseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        responseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 是否收藏
     *
     * @param materialId
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult collect(Integer materialId) {
        WmMaterial wmMaterial = baseMapper.selectById(materialId);
        if (Objects.isNull(wmMaterial)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmMaterial.setIsCollection((short) (wmMaterial.getIsCollection() == 0 ? 1 : 0));
        updateById(wmMaterial);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    /**
     * 删除素材
     *
     * @param materialId
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult delPicture(Integer materialId) {
        WmNewsMaterial wmNewsMaterial = wmNewsMaterialMapper.selectByMaterialId(materialId);

        if (wmNewsMaterial == null) {
            baseMapper.deleteById(materialId);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getErrorMessage());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
